package com.example.tl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhangs
 * @version v1.0
 * @decription ThreadLocal 的第一种使用方式
 * @date 2021/3/29 16:53
 **/
public class One {
    /**
     * 通过该类获取每个线程独有的SimpleDateFormatter
     * 使用ThreadLocal.withInitial()加Lambda方式初始化
     */
    static class DFUtil {
        public static ThreadLocal<SimpleDateFormat> sdf = ThreadLocal
                .withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 通过该类获取每个线程独有的Random
     */
    static class RdmUtil {
        public static ThreadLocal<Random> rdm = new ThreadLocal<Random>() {
            @Override
            protected Random initialValue() {
                return new Random();
            }
        };
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            service.execute(() -> {
                long time = System.currentTimeMillis();
                long l = RdmUtil.rdm.get().nextInt(100000);
                System.out.println(DFUtil.sdf.get().format(new Date(time + l)));
            });
        }
        service.shutdown();
    }
}
